"""
Minimal standalone template scaffold.
Replace __TASK_NAME__ with the desired title when generating.

This file intentionally contains only a small, well-documented
argparse + logging + main() scaffold. Example computation, plotting
and table generation have been removed to keep the generated scripts
lean and safe to run in environments where dependencies may be missing.
"""

from pathlib import Path
import os
import sys

# When running as standalone, assume project root is two levels up
ROOT = Path(__file__).resolve().parent.parent

try:
    get_logger
except NameError:
    try:
        from src.bootstrap_helpers import get_logger, load_config_from_file
    except Exception:
        def get_logger(name: str = "gmt-template", level: str = "INFO"):
            import logging
            logger = logging.getLogger(name)
            if not logger.handlers:
                logger.addHandler(logging.StreamHandler())
            logger.setLevel(level)
            return logger

        def load_config_from_file(path: str = "config.yaml"):
            return {}


def _build_argparse():
    import argparse
    parser = argparse.ArgumentParser(description='脚手架: 最小化的生成脚本模板')
    parser.add_argument('--dry-run', action='store_true', help='只准备但不执行写出步骤')
    parser.add_argument('--verbose', action='store_true', help='输出详细日志')
    parser.add_argument('--no-run', action='store_true', help='生成但不实际执行主要计算逻辑')
    parser.add_argument('--n-jobs', type=int, default=None, help='并行作业数，覆盖环境变量 N_JOBS')
    return parser


def main(argv=None):
    parser = _build_argparse()
    args = parser.parse_args(argv)

    # config precedence: config.yaml -> ENV vars -> CLI args
    try:
        cfg = load_config_from_file('config.yaml')
    except Exception:
        cfg = {}

    # logging
    log_level = 'DEBUG' if args.verbose else cfg.get('log_level', os.environ.get('LOG_LEVEL', 'INFO'))
    logger = get_logger('generated-script', level=log_level)

    TASK_LABEL = '__TASK_NAME__'

    # Optional start hook from helpers
    _start = globals().get('start')
    start_time = None
    if callable(_start):
        try:
            start_time = _start(TASK_LABEL)
        except Exception:
            start_time = None

    # Ensure plotting style and Chinese font are initialized if helpers are available.
    # This is intentionally lightweight and tolerant: if the helpers are not present
    # (e.g., running in an environment without the project installed), these calls
    # will silently no-op thanks to the fallbacks provided by import_header.py.
    try:
        # Preferred, small wrapper that will set rcParams and try to pick a good CJK font
        _set_plot_style = globals().get('set_plot_style')
        if _set_plot_style and callable(_set_plot_style):
            try:
                _set_plot_style()
            except Exception:
                # swallow errors from style application
                pass
        else:
            # If set_plot_style isn't available, try to detect and set a font directly
            _detect_chinese_font = globals().get('detect_chinese_font')
            if _detect_chinese_font and callable(_detect_chinese_font):
                try:
                    f = _detect_chinese_font()
                    if f:
                        import matplotlib
                        matplotlib.rcParams['font.family'] = f
                        matplotlib.rcParams['font.sans-serif'] = [f]
                        matplotlib.rcParams['axes.unicode_minus'] = False
                except Exception:
                    pass
    except Exception:
        # never fail script generation or execution due to font setup
        pass

    if args.no_run:
        logger.info('no-run 模式，跳过主要计算')
        return

    # Placeholder for main computation: users should implement here.
    logger.info('脚手架已生成 - 在此实现您的主要计算逻辑')

    # Optional end hook
    _end = globals().get('end')
    if callable(_end) and start_time is not None:
        try:
            _end(start_time, TASK_LABEL)
        except Exception:
            logger.debug('结束时回调失败')


if __name__ == '__main__':
    main()
